home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2033 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.4 KB  |  62 lines

  1. Path: unix.sri.com!usenet
  2. From: mklenk@updike.sri.com (Mark Klenk)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Examples of using "volatile"?
  5. Date: 18 Jan 1996 16:43:52 GMT
  6. Organization: SRI International
  7. Message-ID: <4dltc8$9ak@unix.sri.com>
  8. References: <4djoj2$mr1@post.gsfc.nasa.gov>
  9. Reply-To: mklenk@updike.sri.com
  10. NNTP-Posting-Host: 204.75.161.40
  11.  
  12. Stephen Maher wrote:
  13. >
  14. >I'd like a concrete example(s) illustrating a reason to
  15. >use the "volatile" type qualifier.
  16.  
  17.     This is mostly useful for variables or memory locations
  18.     which could be written to by interrupt handlers or other
  19.     processors sharing the same memory space.
  20.  
  21.     Example:  Two processors need to communicate via shared
  22.               memory.  One writes a number to a shared location,
  23.               the other reads it (producer/consumer).
  24.  
  25.     The following implementation of the example is not the best,
  26.     but its point is simply to show the use of the keyword.
  27.  
  28.     producer code:
  29.  
  30.         int main(void)
  31.         {
  32.             int volatile * pnum = (int *)0x0000ffff;
  33.  
  34.             for (i = 0; i < 20000; ++i) {
  35.                 *pnum = i;
  36.             }
  37.             return 0;
  38.         }
  39.  
  40.     consumer code (running on a different processor):
  41.  
  42.         #include <stdio.h>
  43.  
  44.         int main(void)
  45.         {
  46.             int const volatile * pnum = (int const *)0x0000ffff;
  47.  
  48.             while (1) {
  49.                 printf("%d\n", *pnum);
  50.             }
  51.             return 0;
  52.         }
  53.  
  54.     I hope this helps.
  55.  
  56. ---
  57.  
  58. mklenk@coronacorp.com       (Mark Klenk)
  59.  
  60.  
  61.  
  62.